package leetcode;

/**
 * 整数反转
 *
 * @author K
 * @date 2021/11/29 16:45
 */
public class Solution7 {
    public static void main(String[] args) {
        int num = 463847412;
//        int result = reverse(num);
        int result = reverse2(num);
        System.out.println();
    }

    public static int reverse(int x) {
        if (x >= 214748364|| x<=-2147483648) {
            return 0;
        }
        boolean flag = false;
        if (x < 0) {
            flag = true;
        }
        int num = flag ? -x : x;
        int result = 0;
        while (num >= 10) {
            int k = num % 10;
            result = k * 10 + result * 10;
            num = num / 10;
        }
        result = result + num;
        return flag ? -result : result;
    }

    public static int reverse2(int x) {
        int ans = 0;
        while (x != 0) {
            int pop = x % 10;
            if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
                return 0;
            if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
                return 0;
            ans = ans * 10 + pop;
            x /= 10;
        }
        return ans;
    }

}
